package leetcode.queue;

/**
 * @author cyt
 * @create 2020-12-08 19:32
 */
public class T622 {

    private int size;
    private int[] elements;
    private int front;

    /**
     * Initialize your data structure here. Set the size of the queue to be k.
     */
    public T622(int k) {
        elements = new int[k];
    }

    /**
     * Insert an element into the circular queue. Return true if the operation is successful.
     */
    public boolean enQueue(int value) {
        if (size == elements.length) {
            return false;
        }
        int index = getIndex(size);
        size++;
        elements[index] = value;
        return true;
    }

    /**
     * Delete an element from the circular queue. Return true if the operation is successful.
     */
    public boolean deQueue() {
        if (size == 0) {
            return false;
        }
        elements[front] = 0;
        front = getIndex(1);
        size--;
        return true;
    }

    /**
     * Get the front item from the queue.
     */
    public int Front() {
        if (size == 0) {
            return -1;
        }
        return elements[front];
    }

    /**
     * Get the last item from the queue.
     */
    public int Rear() {
        if (size == 0) {
            return -1;
        }
        int ans = elements[getIndex(size - 1)];
        return ans;
    }

    /**
     * Checks whether the circular queue is empty or not.
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Checks whether the circular queue is full or not.
     */
    public boolean isFull() {
        return size == elements.length;
    }

    private int getIndex(int bias) {
        return (front + bias) % elements.length;
    }

    public static void main(String[] args) {
        T622 t622 = new T622(3);
        /*
        ["MyCircularQueue","enQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Rear"]
        [[3],[1],[2],[3],[4],[],[],[],[4],[]]
           3 2 1
           3
           4 2 1
           4
           2 1
        */
        System.out.println(t622.enQueue(1));
        System.out.println(t622.enQueue(2));
        System.out.println(t622.enQueue(3));
        System.out.println(t622.enQueue(4));
        System.out.println(t622.Rear());
        System.out.println(t622.isFull());
        System.out.println(t622.deQueue());
        System.out.println(t622.enQueue(4));
        System.out.println(t622.Rear());
    }
}

